<template>
    <div>
        <!-- 输入框和查询按钮 -->
        <input v-model="searchName" placeholder="请输入姓名">
        <input v-model="searchWorkNumber" placeholder="请输入工号">
        <!-- 新增：部门选择器 -->
        <select v-model="selectedDepartment">
            <option value="">请选择部门</option>
            <option v-for="dept in departments" :key="dept.id" :value="dept.id">
                {{ dept.departName }}
            </option>
        </select>
        <button @click="search">查询</button>
        <button @click="resetSearch">重置</button>

        <!-- 月份切换按钮 -->
        <button @click="prevMonth">上一月</button>
        <button @click="nextMonth">下一月</button>
        <button @click="exportToExcel">导出为 Excel</button>
        <h2>{{ formattedCurrentMonth }}</h2>

        <!-- 排班表 -->
        <table>
            <thead>
                <tr>
                    <!-- 人员姓名和工号各占两行 -->
                    <th rowspan="2">人员姓名</th>
                    <th rowspan="2">工号</th>
                    <!-- 动态生成日期 -->
                    <th v-for="day in daysInMonth" :key="day">
                        {{ day }} <!-- 日期 -->
                    </th>

                </tr>
                <tr>
                    <!-- 动态生成日期和对应的星期 -->
                    <th v-for="day in daysInMonth" :key="day" :colspan="1">
                        {{ getDayOfWeek(day) }} <!-- 星期 -->
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="personData in uniquePersons" :key="personData.workNumber">
                    <td>{{ personData.name }}</td>
                    <!-- 显示工号 -->
                    <td>{{ personData.workNumber }}</td>
                    <td v-for="day in daysInMonth" :key="`${personData.workNumber}-${day}`">
                        {{ getDataType(personData, day) }}
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
import dayjs from 'dayjs';
import { getAction } from '../../../api/manage';
import * as XLSX from 'xlsx'; // 引入 xlsx 库

export default {
    data() {
        return {
            currentMonth: dayjs(), // 使用dayjs初始化当前月份
            optimizedTestData: [], // 用于存储从后端获取的优化后的数据
            searchName: '', // 姓名查询条件
            searchWorkNumber: '', // 工号查询条件
            selectedDepartment: '', // 新增：部门选择条件
            departments: [], // 新增：部门列表
            dayOfWeekCache: {}, // 缓存星期几的计算结果
            url: {
                getSchedulingRecord: '/scheduling/scheduling/getSchedulingRecord',
                getDepartments: '/sys/sysDepart/listAll', // 假设有一个接口获取部门列表
            },
        };
    },
    computed: {
        daysInMonth() {
            return this.currentMonth.daysInMonth(); // 当前月份的天数
        },
        uniquePersons() {
            // 使用Map确保每个人员的唯一性，键为工号
            const personsMap = new Map();
            this.optimizedTestData.forEach(item => {
                if (!personsMap.has(item.workNumber)) {
                    personsMap.set(item.workNumber, item);
                }
            });
            return Array.from(personsMap.values());
        },
        formattedCurrentMonth() {
            // 格式化当前月份为yyyy-MM格式
            return this.currentMonth.format('YYYY-MM');
        },
    },
    mounted() {
        this.getSchedulingRecord(this.currentMonth.format('YYYY-MM'));
        this.fetchDepartments(); // 新增：加载部门列表
    },
    methods: {
        prevMonth() {
            this.currentMonth = this.currentMonth.subtract(1, 'month');
            this.search(); // 更新月份后重新查询
        },
        nextMonth() {
            this.currentMonth = this.currentMonth.add(1, 'month');
            this.search(); // 更新月份后重新查询
        },
        getDataType(personData, day) {
            const dateString = this.currentMonth.date(day).format('YYYY-MM-DD');
            if (personData.schedule[dateString]) {
                return personData.schedule[dateString].type;
            } else {
                return ''; // 如果没有匹配的数据，则返回空字符串或其他默认值
            }
        },
        getDayOfWeek(day) {
            const dateString = this.currentMonth.date(day).format('YYYY-MM-DD');
            if (!this.dayOfWeekCache[dateString]) {
                const dayOfWeekIndex = dayjs(dateString).day();
                const weekDaysCN = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                this.dayOfWeekCache[dateString] = weekDaysCN[dayOfWeekIndex];
            }
            return this.dayOfWeekCache[dateString];
        },
        search() {
            // 调用查询方法并传递所有需要的参数
            this.getSchedulingRecord(
                this.currentMonth.format('YYYY-MM'),
                this.searchName,
                this.searchWorkNumber,
                this.selectedDepartment // 新增：传递部门参数
            );
        },
        resetSearch() {
            // 清空查询条件
            this.searchName = '';
            this.searchWorkNumber = '';
            this.selectedDepartment = ''; // 新增：清空部门选择
            // 重新加载数据
            this.getSchedulingRecord(this.currentMonth.format('YYYY-MM'));
        },
        getSchedulingRecord(month, name = '', workNumber = '', departmentId = '') {
            let params = `?month=${month}`;
            if (name) params += `&name=${encodeURIComponent(name)}`;
            if (workNumber) params += `&workNumber=${encodeURIComponent(workNumber)}`;
            if (departmentId) params += `&departmentId=${encodeURIComponent(departmentId)}`;

            getAction(this.url.getSchedulingRecord + params).then((res) => {
                if (res.success) {
                    console.log(res.result)
                    this.optimizedTestData = res.result; // 直接使用优化后的数据
                } else {
                    this.$message.warning(res.message)
                }
            }).catch(error => {
                console.error("Failed to fetch scheduling record:", error);
                this.$message.error("加载排班信息失败，请检查网络连接或稍后再试");
            })
        },
        fetchDepartments() {
            // 获取部门列表
            getAction(this.url.getDepartments).then((res) => {
                if (res.success) {
                    this.departments = res.result; // 假设返回的部门数据格式为 [{ id: 1, name: '技术部' }, ...]
                } else {
                    this.$message.warning(res.message);
                }
            }).catch(error => {
                console.error("Failed to fetch departments:", error);
                this.$message.error("加载部门信息失败，请检查网络连接或稍后再试");
            });
        },
        exportToExcel() {
            // 获取表格元素
            const table = document.querySelector('table');

            // 将表格转换为工作簿对象
            const workbook = XLSX.utils.table_to_book(table, { sheet: "Sheet1" });

            // 导出 Excel 文件
            XLSX.writeFile(workbook, `${this.formattedCurrentMonth}_排班表.xlsx`);
        },
    },
};
</script>

<style scoped>
/* 添加一些基本样式 */
table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    padding: 8px;
    text-align: center;
    border: 1px solid #ddd;
}

th[scope='row'] {
    vertical-align: middle;
}

input {
    margin-right: 10px;
}

button {
    margin-right: 5px;
}
</style>